package com.qire.manhua.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.manhua.R;

import androidx.annotation.Nullable;

/**
 *  电池状态显示控件
 */
public class BatteryStateView extends View {

    private Drawable batteryStateBg;
    private Rect electricCapacityRect;
    private Rect progressRect;
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int percentage = 50;
    private int alertValue = 25;

    private BatteryReceiver batteryReceiver;

    public BatteryStateView(Context context) {
        super(context);
        init();
    }

    public BatteryStateView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BatteryStateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

        batteryStateBg = getResources().getDrawable(R.drawable.app_comic_reader_battery_state, null);

        //全局可用不受Activity影响,为null可做一次性获取，不用unregisterReceiver;
//        Intent batteryInfoIntent = getContext().getApplicationContext().registerReceiver( null ,intentFilter);

        batteryReceiver = new BatteryReceiver(getContext());
        Intent batteryInfoIntent = batteryReceiver.registerReceiver();
        if(batteryInfoIntent != null) {
            int current = batteryInfoIntent.getExtras().getInt("level");// 获得当前电量
            int total = batteryInfoIntent.getExtras().getInt("scale");// 获得总电量
            percentage = current * 100 / total;
        }

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        batteryReceiver.unregisterReceiver();
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
        electricCapacityRect = new Rect(0, 0, getWidth(), getHeight());
        progressRect = new Rect(electricCapacityRect);
        batteryStateBg.setBounds(electricCapacityRect);
        updatePercentage(percentage);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setColor(Color.WHITE);//(percentage < alertValue ? Color.RED : Color.GREEN);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        canvas.save();
        Rect clipRect = new Rect(electricCapacityRect);
        clipRect.left+= EquipmentInfoUtil.dip2px(0.5f);
        clipRect.right-= EquipmentInfoUtil.dip2px(2f);
        canvas.clipRect(clipRect);
        canvas.drawRect(progressRect, paint);
        canvas.restore();

        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(EquipmentInfoUtil.dip2px(1f));
        paint.setStyle(Paint.Style.STROKE);
        batteryStateBg.draw(canvas);
        canvas.drawRoundRect(new RectF(clipRect), 5, 5, paint);
    }

    /**
     * 更新电量百分比
     * @param percentage 电量半分比设置，一个不能小于0且不大于100的数*/
    public void updatePercentage(int percentage) {
        //View 尚未初始化
        if(progressRect == null) {
            return;
        }
        percentage = Math.max(percentage, 0);
        percentage = Math.min(percentage, 100);
        this.percentage = percentage;
        int offset = progressRect.width() * percentage / 100 ;
        progressRect.offsetTo(-progressRect.width(), 0);
        progressRect.offset(offset, 0);
        invalidate();
    }

    /**
     * 设置境界值，当电量低于该值则容量为红色
     * @param alertValue 警戒值，百分比数值,0到100以内有效,默认25
     * */
    public void setAlertValue(int alertValue) {
        this.alertValue = alertValue;
    }

    /**
     * 监听获取手机系统剩余电量
     */
    public class BatteryReceiver extends BroadcastReceiver {

        private final Context context;
        private boolean isRegistered = false;

        public BatteryReceiver(Context context) {
            this.context = context;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            int current = intent.getExtras().getInt("level");// 获得当前电量
            int total = intent.getExtras().getInt("scale");// 获得总电量
            int percent = current * 100 / total;
            updatePercentage(percent);
        }

        public Intent registerReceiver() {
            if(isRegistered) {
                return null;
            }
            isRegistered = true;
            IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            return context.registerReceiver(this, intentFilter);
        }

        public void unregisterReceiver() {
            if(isRegistered) {
                context.unregisterReceiver(this);
            }
        }

    }

}
